#include <main.h>
#include "images.h"
#include "test_imageshow.h"
#include "image_tool.h"

u8_t image_index = 0;
struct surface_t *screen;

static inline void image_index_add()
{
    image_index = (image_index+1)%N_images;
}
static inline void image_index_sub()
{
    image_index = (image_index+N_images-1)%N_images;
}

static inline void show_current_image()
{
    s5pv210_screen_swap();
    show_image_fullscreen(screen, images_g[image_index]);
    s5pv210_screen_flush();
}
static inline void show_next_image()
{
    image_index_add();
    show_current_image();
}
static inline void show_last_image()
{
    image_index_sub();
    show_current_image();
}

u32_t switch_time_ms = 2500;
u8_t auto_switch = 1;
u8_t time_index = 6;
#define N_time_table 12 
u32_t time_table[N_time_table] = {100, 300, 500, 1000, 1500, 2000, 2500, 3000, 5000, 10000, 15000, 20000};
static inline void time_increase()
{
    if(time_index+1 <= N_time_table-1)
    {
        time_index++;
        switch_time_ms = time_table[time_index];
        serial_printf(2, "time increased to %d ms\r\n",switch_time_ms);
    }
}
static inline void time_decrease()
{
    if(time_index-1 >= 0)
    {
        time_index--;
        switch_time_ms = time_table[time_index];
        serial_printf(2, "time decreased to %d ms\r\n",switch_time_ms);
    }
}

void my_tick_task(u32_t jiffies, u32_t tick_hz)
{
    if(auto_switch == 0) 
        return ;
    static u32_t pre_switch_time_ms;
    u32_t now_time_ms = jiffies*1000/tick_hz;
    if(now_time_ms > pre_switch_time_ms + switch_time_ms) //u32_t溢出兼容
    {
        show_next_image();
        pre_switch_time_ms = now_time_ms;
    }
}

void test_imageshow()
{
    load_images();
    u32_t key_up = 0;
    u32_t key_down = 0;
    screen = s5pv210_screen_surface();
    show_current_image();
    while(1)
    {
        if(get_key_event(&key_up, &key_down))
        {
            if(key_down&KEY_NAME_DOWN)
            {
                show_next_image();
                auto_switch = 0;
            }
            else if(key_down&KEY_NAME_UP)
            {
                show_last_image();
                auto_switch = 0;
            }
            else if(key_down&KEY_NAME_LEFT)
            {
                time_increase();
            }
            else if(key_down&KEY_NAME_RIGHT)
            {
                time_decrease();
            }
            else if(key_down&KEY_NAME_BACK)
            {
                auto_switch = 1;
            }
        }
    }
    while(1);
}


